package com.king.springcloud.controller;

import com.king.springcloud.entities.CommonResult;
import com.king.springcloud.entities.PaymentEntity;
import com.king.springcloud.lb.LoadBalanced;
import com.netflix.loadbalancer.IRule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @author king
 * @data 2020/7/30 23:03
 */
@RestController
@Slf4j
@RequestMapping("/consumer")
public class OrderController {
    // 单机
//    public static final String PAYMENT_URL = "http://127.0.0.1:8001";
    // 集群
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private LoadBalanced loadBalanced;
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/payment/create")
    public CommonResult<PaymentEntity> create(PaymentEntity paymentEntity){
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", paymentEntity, CommonResult.class);
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<PaymentEntity> getPaymentById(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }

    @GetMapping("/payment/getForEntity/{id}")
    public CommonResult<PaymentEntity> getPaymentById2(@PathVariable("id") Long id){
        ResponseEntity<CommonResult> result = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        if (result.getStatusCode().is2xxSuccessful()) {
            return result.getBody();
        } else {
            return new CommonResult<>(444, "查询不到数据");
        }
    }


    @GetMapping("/payment/lb")
    public String getPaymentLB(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (null == instances || instances.isEmpty()) {
            return null;
        }
        ServiceInstance serviceInstance = loadBalanced.instance(instances);

        return restTemplate.getForObject(serviceInstance.getUri() + "/payment/lb", String.class);
    }

    /**
     * zipkin + sleuth
     * @return
     */
    @GetMapping("/consumer/payment/zipkin")
    public String paymentZipkin(){
        return restTemplate.getForObject("http://localhost:8001" + "/payment/zipkin/", String.class);
    }
}
